<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <!-- 上传组件中的 + 号图标 -->
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <!-- 上传时的进度条 -->
    <el-progress v-if="showProgress" type="circle" :percentage="percentage" class="progress" />
  </el-upload>
</template>

<script>
const COS = require('cos-js-sdk-v5')

var cos = new COS({
  SecretId: 'AKIDQecKNCpCI7fvuc3D6yd3EArJWUCeqnUv',
  SecretKey: 'JQIvIPHtKXWGl13qOhlbCYfZFgsqa4KM'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      percentage: 0, // 上传进度
      showProgress: false // 控制进度条是否显示
    }
  },
  methods: {
    // 图片上传方法
    upload(files) {
      if (files.file) {
        // 让进度条展示
        this.showProgress = true
        cos.putObject({
          Bucket: 'hr-1252326128', /* 必须 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 必须字段, 对象在存储桶中的唯一标识, 一般是上传的文件名称 */
          StorageClass: 'STANDARD',
          Body: files.file, // 上传文件对象
          // 上传的进度
          onProgress: (progressData) => {
            console.log(JSON.stringify(progressData))
            this.percentage = progressData.percent * 100
          }
          // 上传成功 失败的回调
        }, (err, data) => {
          if (err === null && data.statusCode === 200) {
            this.imageUrl = `https://${data.Location}`
          }
          // 让进度条隐藏
          this.showProgress = false
        })
      }
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
